package com.lucky.contract.controller;

import com.lucky.contract.ContractApplication;
import com.lucky.contract.common.ResultModel;
import com.lucky.contract.entity.SysUser;
import com.lucky.contract.service.SysUserService;
import com.lucky.contract.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(ContractApplication.class);

    @Resource
    private SysUserService sysUserService;

    @RequestMapping(value = "/userLogin")
    public String index(){
        return "login";
    }

    @RequestMapping(value = "/login")
    @ResponseBody
    public Object login(SysUser user, HttpServletRequest request, HttpServletResponse response, ResultModel result){
        Map<String, Object> map = new HashMap<>();
        try {
            if(user != null && StringUtils.isNotBlank(user.getUserName()) && StringUtils.isNotBlank(user.getPassword())) {
                user.setPassword(MD5.getMD5ofStr(user.getPassword()));
                SysUser loginUser = sysUserService.login(user);
                if(loginUser != null) {
                    request.getSession().setAttribute("loginPersonId", loginUser);
                    result.setCode(0);
                    result.setMsg("登陆成功！");
                    log.info(user.getUserName() + "登陆成功！！！");
                } else {
                    result.setCode(1);
                    result.setMsg("用户名或密码错误！");
                }
            } else {
                result.setCode(1);
                result.setMsg("登录信息不能为空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return result;
    }
}

